package HuffMantree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HuffmanTree {
    public static void main(String[] args) {
        int[] arr = {3,6,15,20};
        Node HuffmanTree = createHuffmanTree(arr);
        if (HuffmanTree != null) {
            HuffmanTree.preOrder();
        }
    }
    public static Node createHuffmanTree(int[] arr) {
        List<Node> nodeList = new ArrayList<>();
        for (int item : arr) {
            nodeList.add(new Node(item));
        }
        while (nodeList.size() > 1){
            // 从小到大排序list
            Collections.sort(nodeList);
            // 取出前两个最小的，第一个作为左节点，第二个作为右节点
            Node leftNode = nodeList.get(0);
            Node rightNode = nodeList.get(1);
            // 将权重+路径和赋值给父节点，将父节点的左右节点挂上
            Node parentNode = new Node(leftNode.getValue()+rightNode.getValue());
            parentNode.setLeft(leftNode);
            parentNode.setRight(rightNode);
            // 移除最小的两个节点，将父节点放入list集合中，进行下一轮
            nodeList.remove(leftNode);
            nodeList.remove(rightNode);
            nodeList.add(parentNode);
        }
        // 返回最终的根节点
        return nodeList.get(0);
    }
}
class Node implements Comparable<Node> {
    private int value;
    private Node left;
    private Node right;

    public Node(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }
    // 从小到大排序
    @Override
    public int compareTo(Node node) {
        return this.value - node.value;
    }
    // 前序遍历
    public void preOrder(){
        System.out.println(this.toString());
        if(this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }
}
